use crate::models::customers::{self, CreateParams, UpdateParams};
use axum::{
    Json, Router,
    extract::State,
    routing::{get, post},
};
use loco_rs::prelude::*;

pub fn routes() -> Router<AppContext> {
    Router::new()
        .route("/customers", post(create))
        .route("/customers/:id", get(get_by_id))
        .route("/customers/:id", post(update))
        .route("/customers/:id/delete", post(delete))
        .route("/customers/by-email/:email", get(get_by_email))
        .route("/customers/by-group/:group_id", get(get_by_group))
}

async fn create(
    State(state): State<AppContext>,
    Json(params): Json<CreateParams>,
) -> Result<Response> {
    let customer = customers::Model::create(&state.db, params).await?;
    format::json(customer)
}

async fn get_by_id(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    let customer = customers::Model::find_by_id(&state.db, &id).await?;
    format::json(customer)
}

async fn update(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
    Json(params): Json<UpdateParams>,
) -> Result<Response> {
    let customer = customers::Model::update_by_id(&state.db, &id, params).await?;
    format::json(customer)
}

async fn delete(
    State(state): State<AppContext>,
    axum::extract::Path(id): axum::extract::Path<String>,
) -> Result<Response> {
    customers::Model::delete_by_id(&state.db, &id).await?;
    format::json(())
}

async fn get_by_email(
    State(state): State<AppContext>,
    axum::extract::Path(email): axum::extract::Path<String>,
) -> Result<Response> {
    let customer = customers::Model::find_by_email(&state.db, &email).await?;
    format::json(customer)
}

async fn get_by_group(
    State(state): State<AppContext>,
    axum::extract::Path(group_id): axum::extract::Path<String>,
) -> Result<Response> {
    let customers = customers::Model::find_by_group(&state.db, &group_id).await?;
    format::json(customers)
}
